<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="'登录'+${projectName}"></title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="icon" th:href="@{favicon.ico}">
    <link rel="stylesheet" th:href="@{/js/layuiadmin-1.2.1/layui/css/layui.css?v=1}" media="all"/>
    <link rel="stylesheet" th:href="@{dhecp/css/dh-login.css?v=6}" />
    <link rel="stylesheet" th:href="@{dhecp/css/dh-icon.css?v=1}" />
    <script>
        if(window.top!==window.self){window.top.location=window.location};
    </script>
    <style type="text/css">
		.layui-form-checkbox{margin-right:0}
		.copyright{text-align:center;height:40px;line-height:20px;font-size:13px;width: 500px;color: #eee;position: fixed;left: 50%;bottom: 0%;margin-left: -250px;}
		.copyright a{color:#eee;}
    </style>
</head>
<!-- <canvas> -->
<!-- </canvas> -->
	<div class="layui-container">
	    <div class="admin-login-background">
	        <div class="layui-form login-form">
				<div class="logo-title">
					<h1 th:text="${projectName}"></h1>
				</div>
	        	<image mode="aspectFit" style="vertical-align:top;" class="login-lt-img" src="/img/bag.png?v=2"></image>
				<form class="layui-form login-info-box">
					<h1 style="font-weight:700;color:#33a1ff;" class="login-title">欢迎登录</h1>
					<!-- <hr class="hr20" style="margin-bottom: 8%;"> -->
					<div class="layui-form-item">
						<label class="dhicon dh-user-circle" for="username"></label>
						<select id="user_select" lay-filter="user_select">
						</select>
						<input id="userName" name="username" value="" autocomplete="off" placeholder="用户名" type="text" style="margin-top:-38px" class="layui-input login-input-username" lay-verify="required" lay-reqText="请输入账号！">
					</div>
					<div class="layui-form-item">
						<label class="dhicon dh-unlock" for="password"></label>
						<input id="passWord" name="password" autocomplete="new-password" type="password" class="layui-input" lay-verify="required" lay-reqText="请输入密码！">
					</div>
					<div class="layui-form-item">
						<label class="dhicon dh-lujing1236" for="mandator"></label>
						<select name="mandator" id="mandator">
							<option value="">请选择被代理用户</option>
<!-- 							<option th:each="ml:${@baseinfosimple.getUserAgentMandator('test')}" th:value="${ml.userId}" th:text="${ml.userName}"></option> -->
						</select>
<!-- 						<input name="mandator" value="test" autocomplete="off" placeholder="被代理用户" type="text" class="layui-input"> -->
					</div>
					<div class="layui-form-item row m-t" th:if="${captchaEnabled==true}">
						<label class="layui-icon layui-icon-vercode" for="validatecode"></label>
						<input type="text" name="validatecode" lay-verify="required|captcha" placeholder="验证码" autocomplete="off" class="layui-input verification captcha" value="">
						<div class="captcha-img">
							<a href="javascript:void(0);" title="点击更换验证码">
								<img th:src="@{captcha/captchaImage(type=${captchaType})}" class="imgcode" width="85%"/>
							</a>
						</div>
					</div>
					<div class="layui-form-item checkbox-custom" th:classappend="${captchaEnabled==false} ?'m-t'">
						<input type="checkbox" id="rememberme" name="rememberme" value="true" title="记住我" th:checked="${captchaEnabled==false}">
<!-- 						<div style="float:right"> -->
<!-- 							<input type="checkbox" id="choose_mandator" value="true" title="代理用户" lay-filter="choose_mandator" checked> -->
<!-- 						</div> -->
					</div>
					<input type="button" value="登录" class="layui-btn layui-btn-fluid" lay-submit lay-filter="login" id="login" style="background-color:#0086e6">
				</form>
				<div class="copyright">
					<p>本系统建议使用<a href="https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2583F227-EB89-F139-FA25-14AACAD46C66%7D%26lang%3Dzh-CN%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe">谷歌</a>、
						<a href="https://www.baidu.com/link?url=1pX667wccAXD2Zrbr9-VLFwJtnR-OpF3LiXxSzPLNBfaEPQoOWsOK59vRjaN0V8jhVF7_GLGnllCaMDj2n5GKDbzcj0xcexPkvpFc7o29Fdt4NHHlEPIbmZeJ4i2qQm9KZWJZ58u8LoQDsjTr-MO8KlzaaKlHLHsR9bmpwJlEoP7vF_2kRflZeKIvRnkrOjzYWoGiZEyoZ9yEQ9dz6npRa&wd=&eqid=b2c0060500055f9f000000065e5ccfc2" target="_blank">360极速模式</a>等主流浏览器　 版权所有  @ <a href="https://erpmyself.mini-ease.com/" target="_blank">福建省逸思信息科技有限公司</a></p>
				</div>
	        </div>
	    </div>
	</div>
<script th:inline="javascript"> 
var ctx = [[@{/}]]; 
var captchaType = [[${captchaType}]];
var pcId = [[${pcId}]];
var rememberUser = [[${rememberUser}]];
var publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKthHRNQkJ8W3E2YVQEhXrOl6GrPIhNV8VH3BTCXqwSeetVfZNLM2bpv1AcA215xDnGmKI7f8mwW5V8Z/g4sqQkCAwEAAQ==';
</script>
<script th:src="@{/js/jquery/jquery.min.js}"></script>
<script th:src="@{/js/jquery/jquery.cookie.js}"></script>
<script th:src="@{/dhecp/js/md5.js}"></script>
<script th:src="@{/js/plugins/jsencrypt/jsencrypt.min.js}"></script>
<script th:src="@{/js/layuiadmin-1.2.1/layui/layui.js}"></script>
<!-- <script th:src="@{/dhecp/js/canvas.js}"></script> -->
<script>
	// 加密
	function encrypt(txt) {
		const encryptor = new JSEncrypt()
		encryptor.setPublicKey(publicKey) // 设置公钥
		return encryptor.encrypt(txt) // 对数据进行加密
	}
    layui.use(['form', 'jquery'], function () {
        var form = layui.form, $ = layui.$;
		var arrCookie = [];
		//服务端rememberUser参数有值，以这个为准，没值取cookie
		if(rememberUser != ""){
			$('#userName').val(rememberUser);
			arrCookie.push(rememberUser);
		}else {
			arrCookie = $.cookie('dhecp_cookie') ? $.cookie('dhecp_cookie').split(",") : [];
			$('#userName').val(arrCookie[0]);
		}
        refreshMandator();
		$.each(arrCookie,function(k,v){//通过cookie给下拉框赋值
			$('#user_select').append(new Option(v,v));
		})
		form.render();//重新渲染下拉框
        form.on('select(user_select)', function (e) {//监听下拉框,给账号密码赋值
            $('#userName').val($('#user_select').find("option:selected").text());
            refreshMandator();
        });
       	$("#userName").blur(function(){//监听账号输入来加载代理人下拉框
       		refreshMandator();
		}) 
//        	form.on('checkbox(choose_mandator)', function(data){//监听checkbox是否开启代理人下拉框
// 			if(data.elem.checked){
// 				$('#mandator').removeAttr('disabled');
// 				form.render('select');
// 			}else{
// 				$('#mandator').attr("disabled",'disabled');
// 				form.render('select');
// 			}
// 		});
        form.on('submit(login)', function (data) {
            var index;
            var username = $("input[name='username']").val().toLowerCase();
            var password = $("input[name='password']").val();
//             if($("#mandator").val() && $('#choose_mandator')[0].checked){//判断代理人勾选并有选择，无则传入登录账号
           	var mandator = $("#mandator").val();
//             }else{
//             	var mandator =username;
//             }
            var validateCode = $("input[name='validatecode']").val();
            var rememberMe = $("input[name='rememberme']").is(':checked');
            $.ajax({
                type: "post",
                url: "/login",
                data: {
                    "username": username,
                    "password": encrypt(password),
                    "mandator": mandator,
                    "validateCode" : validateCode,
                    "rememberMe": rememberMe,
					"pcId":pcId
                },
                beforeSend: function () {
                    index = layer.msg('正在登录', {icon: 16, shade: 0.3});
                },
                success: function (r) {
                    layer.close(index);
                    if (r.code == 0) {//验证成功
//                     	expires：（Number|Date）有效期；设置一个整数时，单位是天；也可以设置一个日期对象作为Cookie的过期日期；
//                     	path：（String）创建该Cookie的页面路径,/为根目录下，不填写则为当前页面下；
//                     	domain：（String）创建该Cookie的页面域名；
//                     	secure：（Booblean）如果设为true，那么此Cookie的传输会要求一个安全协议，例如：HTTPS；
//             			删除cookie： $.removeCookie(key,{path:'/'});
                    	if($('#rememberme')[0].checked){
                    		var userStr=username;
                    		$.each(arrCookie,function(v,k){
                    			if(k!=username && v<4)userStr+=','+k;//只保留5个账号
                    		})
                    		$.cookie('dhecp_cookie', userStr, { expires: 365, path: '/' });//存放cookie
                    	}
                		$.cookie('dhecp_lockScreen', hex_hmac_md5("dhecp"+username,username), { expires: 1, path: '/' });//存放cookie
                        location.href = '/index';
                    } else {
                    	// if(r.data && r.data.repeatLogin == 1){
                    	// 	setTimeout(function(){
                    	// 		location.href = '/index';
        		        //     }, 2000);
                    	// }
                    	layer.msg(r.msg, {icon: 5});
                    }
                }
            });
            return false;
        });

        function validateKickout() {
            var temp = getParam("kickout");
            if (getParam("kickout") == "1") {
                layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
                    icon: 0,
                    title: "系统提示"
                 },
                 function(index) {
                    //关闭弹窗
                    layer.close(index);
                    if (top != self) {
                        top.location = self.location;
                    } else {
                        var url  =  location.search;
                        if (url) {
                            var oldUrl  = window.location.href;
                            var newUrl  = oldUrl.substring(0,  oldUrl.indexOf('?'));
                            self.location  = newUrl;
                        }
                    }
                 });
            }
        }
        function getParam(paramName) {
            var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURI(r[2]);
            return null;
        }
        $(function() {
            $('.imgcode').click(function() {
                var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
                $(".imgcode").attr("src", url);
            });
            validateKickout();
        });
        function refreshMandator(){//刷新代理人下拉框
        	$("#mandator").empty();
       		$.ajax({
    			url: "system/agent/mandatorlist?userName="+$("#userName").val(),
    			type: 'get',
    			dataType: "json",
    			success: function(res) {
    				$.each(res.data,function(k,v){
    					$('#mandator').append(new Option(v.userName,v.userId));
    				});
    				form.render();
    			}
    		});
        };
        $(document).keydown(function (e) {
        	if (e.keyCode === 13) {
           		$("#login").trigger("click");
        	}
       	});
    });
</script>
</body>
</html>